<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Neon Snake | 科技炫酷贪吃蛇</title>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Orbitron', sans-serif;
            background-color: #0a0a2e;
            color: #00f7ff;
            overflow: hidden;
            touch-action: manipulation;
            height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .game-header {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .game-title {
            font-size: 2.5rem;
            text-shadow: 0 0 15px #00f7ff;
            margin-bottom: 10px;
            letter-spacing: 3px;
        }
        
        .game-container {
            position: relative;
            width: 100%;
            max-width: 800px;
            max-height: 600px;
            aspect-ratio: 4/3;
            margin: 0 auto;
        }
        
        #gameCanvas {
            width: 100%;
            height: 100%;
            border: 2px solid #00f7ff;
            box-shadow: 0 0 30px rgba(0, 247, 255, 0.3);
            display: block;
        }
        
        .control-panel {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            max-width: 800px;
            margin-top: 15px;
            padding: 0 10px;
        }
        
        #score {
            font-size: 1.5rem;
            text-shadow: 0 0 10px #00f7ff;
            letter-spacing: 2px;
        }
        
        .speed-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        #speedControl {
            -webkit-appearance: none;
            width: 150px;
            height: 8px;
            background: linear-gradient(90deg, #00ff88, #ff0066);
            border-radius: 4px;
            outline: none;
            opacity: 0.7;
            transition: opacity 0.2s;
        }
        
        #speedControl:hover {
            opacity: 1;
        }
        
        #speedControl::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #00f7ff;
            cursor: pointer;
            box-shadow: 0 0 10px rgba(0, 247, 255, 0.8);
        }
        
        .settings-panel {
            display: flex;
            gap: 15px;
            margin-top: 15px;
        }
        
        select, button {
            background: rgba(0, 0, 0, 0.3);
            color: #00f7ff;
            border: 1px solid #00f7ff;
            padding: 8px 12px;
            border-radius: 4px;
            font-family: 'Orbitron', sans-serif;
            cursor: pointer;
            outline: none;
        }
        
        select option {
            background: #0a0a2e;
        }
        
        button:hover {
            background: rgba(0, 247, 255, 0.1);
        }
        
        /* 移动端虚拟摇杆 */
        .virtual-joystick {
            position: absolute;
            bottom: 30px;
            right: 30px;
            width: 100px;
            height: 100px;
            background: rgba(0, 247, 255, 0.1);
            border-radius: 50%;
            border: 2px solid rgba(0, 247, 255, 0.3);
            display: none;
            touch-action: none;
            z-index: 10;
        }
        
        .joystick-knob {
            position: absolute;
            width: 40px;
            height: 40px;
            background: radial-gradient(circle, #00f7ff, #00a1ff);
            border-radius: 50%;
            top: 30px;
            left: 30px;
            box-shadow: 0 0 15px rgba(0, 247, 255, 0.5);
            transition: transform 0.1s;
        }
        
        .mobile-controls {
            position: absolute;
            bottom: 30px;
            left: 30px;
            display: none;
            gap: 15px;
            z-index: 10;
        }
        
        .mobile-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(0, 247, 255, 0.2);
            border: 2px solid rgba(0, 247, 255, 0.5);
            color: #00F7FF;
            font-size: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            touch-action: manipulation;
            user-select: none;
            outline: none;
        }
        
        .mobile-btn:active {
            background: rgba(0, 247, 255, 0.4);
            transform: scale(0.95);
        }
        
        @media (max-width: 768px) {
            .game-title {
                font-size: 1.8rem;
            }
            
            #score {
                font-size: 1.2rem;
            }
            
            .virtual-joystick {
                display: block;
            }
            
            .mobile-controls {
                display: flex;
            }
            
            .settings-panel {
                flex-direction: column;
                gap: 8px;
            }
        }
        
        /* 游戏菜单 */
        .game-menu {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }
        
        .menu-title {
            font-size: 3rem;
            color: #00f7ff;
            margin-bottom: 30px;
            text-shadow: 0 0 15px #00f7ff;
        }
        
        .menu-options {
            display: flex;
            flex-direction: column;
            gap: 15px;
            width: 80%;
            max-width: 300px;
        }
        
        .menu-btn {
            padding: 15px;
            font-size: 1.2rem;
            background: rgba(0, 247, 255, 0.1);
            border: 2px solid #00f7ff;
            color: #00f7ff;
            border-radius: 8px;
            cursor: pointer;
            text-align: center;
            transition: all 0.3s;
        }
        
        .menu-btn:hover {
            background: rgba(0, 247, 255, 0.3);
            transform: scale(1.05);
        }
        
        .hidden {
            display: none;
        }
        
        /* 游戏开始倒计时 */
        .countdown {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 10rem;
            color: #00f7ff;
            text-shadow: 0 0 20px #00f7ff;
            z-index: 50;
            background-color: rgba(0, 0, 0, 0.5);
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }
        
        .countdown.active {
            opacity: 1;
        }
        
        /* 游戏提示 */
        .game-hint {
            position: absolute;
            top: 10px;
            left: 0;
            width: 100%;
            text-align: center;
            color: #00f7ff;
            font-size: 1rem;
            z-index: 10;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="game-header">
        <h1 class="game-title">NEON SNAKE</h1>
    </div>
    
    <div class="game-container">
        <canvas id="gameCanvas"></canvas>
        
        <div class="countdown" id="countdown"></div>
        <div class="game-hint" id="gameHint"></div>
        
        <div class="game-menu" id="mainMenu">
            <h2 class="menu-title">NEON SNAKE</h2>
            <div class="menu-options">
                <button class="menu-btn" id="startClassic">经典模式</button>
                <button class="menu-btn" id="startAI">AI对战</button>
                <select class="menu-btn" id="themeSelect">
                    <option value="cyber">赛博主题</option>
                    <option value="pixel">像素主题</option>
                    <option value="neon">霓虹主题</option>
                </select>
                <select class="menu-btn" id="difficultySelect">
                    <option value="easy">简单</option>
                    <option value="normal" selected>普通</option>
                    <option value="hard">困难</option>
                </select>
            </div>
        </div>
        
        <div class="virtual-joystick">
            <div class="joystick-knob"></div>
        </div>
        
        <div class="mobile-controls">
            <button class="mobile-btn" id="mobilePauseBtn">⏸</button>
        </div>
    </div>
    
    <div class="control-panel hidden" id="controlPanel">
        <span id="score">SCORE: 0</span>
        <div class="speed-control">
            <span>SPEED:</span>
            <input type="range" id="speedControl" min="1" max="10" value="5">
        </div>
    </div>
    
    <div class="settings-panel hidden" id="settingsPanel">
        <button id="pauseBtn">暂停</button>
        <button id="menuBtn">菜单</button>
        <select id="themeSwitch">
            <option value="cyber">赛博主题</option>
            <option value="pixel">像素主题</option>
            <option value="neon">霓虹主题</option>
        </select>
    </div>
    
    <script>
        // 游戏常量
        const GRID_SIZE = 20;
        let GRID_COUNT_X = 40;
        let GRID_COUNT_Y = 30;
        
        // 食物类型
        const FOOD_TYPES = {
            normal: { color: '#FF0000', score: 10, effect: null },
            speedUp: { color: '#00FF88', score: 20, effect: 'speed' },
            shield: { color: '#0099FF', score: 15, effect: 'shield' },
            bomb: { color: '#FFA500', score: -5, effect: 'bomb' }
        };
        
        // 主题配置
        const THEMES = {
            cyber: {
                snakeHeadColor: '#00FF88',
                snakeBodyColor: '#00F7FF',
                foodColor: '#FF0066',
                backgroundColor: '#0a0a2e',
                gridColor: 'rgba(0, 247, 255, 0.1)',
                uiColor: '#00F7FF',
                textShadow: '0 0 10px #00f7ff'
            },
            pixel: {
                snakeHeadColor: '#FF0000',
                snakeBodyColor: '#880000',
                foodColor: '#00FF00',
                backgroundColor: '#000000',
                gridColor: 'rgba(100, 100, 100, 0.2)',
                uiColor: '#FFFFFF',
                textShadow: '0 0 10px #ffffff'
            },
            neon: {
                snakeHeadColor: '#FF00FF',
                snakeBodyColor: '#9900FF',
                foodColor: '#00FFFF',
                backgroundColor: '#110022',
                gridColor: 'rgba(153, 0, 255, 0.1)',
                uiColor: '#FF00FF',
                textShadow: '0 0 10px #ff00ff'
            }
        };
        
        // 游戏状态类
        class GameState {
            constructor() {
                this.reset();
            }
            
            reset() {
                this.snake = [{x: 15, y: 15}];
                this.food = this.generateFood();
                this.direction = 'right';
                this.nextDirection = 'right';
                this.speed = 200;
                this.score = 0;
                this.gameOver = false;
                this.paused = false;
                this.specialFood = null;
                this.specialFoodTimer = 0;
                this.comboCount = 0;
                this.comboTimer = null;
                this.particles = [];
                this.gridOffset = 0;
                this.shieldActive = false;
                this.gameStarted = false;
            }
            
            generateFood() {
                let food;
                const types = Object.keys(FOOD_TYPES);
                const weights = [0.7, 0.1, 0.1, 0.1]; // 普通食物70%概率
                let randomValue = Math.random();
                let typeIndex = 0;
                let cumulativeWeight = 0;
                
                for (let i = 0; i < weights.length; i++) {
                    cumulativeWeight += weights[i];
                    if (randomValue <= cumulativeWeight) {
                        typeIndex = i;
                        break;
                    }
                }
                
                const foodType = types[typeIndex];
                
                do {
                    food = {
                        x: Math.floor(Math.random() * GRID_COUNT_X),
                        y: Math.floor(Math.random() * GRID_COUNT_Y),
                        type: foodType
                    };
                } while (this.isPositionOccupied(food.x, food.y));
                
                return food;
            }
            
            isPositionOccupied(x, y) {
                return this.snake.some(segment => segment.x === x && segment.y === y);
            }
        }
        
        // A*算法节点类
        class Node {
            constructor(x, y, parent = null) {
                this.x = x;
                this.y = y;
                this.parent = parent;
                this.g = 0;
                this.h = 0;
                this.f = 0;
            }
        }
        
        // AI蛇类
        class AISnake {
            constructor(game) {
                this.game = game;
                this.path = [];
                this.difficulty = 'normal';
                this.updateInterval = 1000;
                this.lastUpdate = 0;
            }
            
            setDifficulty(difficulty) {
                this.difficulty = difficulty;
            }
            
            update(timestamp) {
                if (timestamp - this.lastUpdate < this.updateInterval) return;
                this.lastUpdate = timestamp;
                
                // 根据难度调整更新频率
                switch(this.difficulty) {
                    case 'easy': this.updateInterval = 1500; break;
                    case 'normal': this.updateInterval = 1000; break;
                    case 'hard': this.updateInterval = 500; break;
                }
                
                this.findPathToFood();
                this.followPath();
            }
            
            findPathToFood() {
                const start = this.game.state.snake[0];
                const target = this.game.state.food;
                const obstacles = this.game.state.snake.slice(1);
                
                this.path = this.aStar(start, target, obstacles);
            }
            
            aStar(start, target, obstacles) {
                const openSet = [new Node(start.x, start.y)];
                const closedSet = new Set();
                const cameFrom = new Map();
                const gScore = new Map();
                const fScore = new Map();
                
                gScore.set(`${start.x},${start.y}`, 0);
                fScore.set(`${start.x},${start.y}`, this.heuristic(start, target));
                
                while (openSet.length > 0) {
                    openSet.sort((a, b) => fScore.get(`${a.x},${a.y}`) - fScore.get(`${b.x},${b.y}`));
                    const current = openSet.shift();
                    
                    if (current.x === target.x && current.y === target.y) {
                        return this.reconstructPath(cameFrom, current);
                    }
                    
                    closedSet.add(`${current.x},${current.y}`);
                    
                    for (const [dx, dy] of [[0,1], [0,-1], [1,0], [-1,0]]) {
                        const neighbor = new Node(current.x + dx, current.y + dy);
                        
                        if (closedSet.has(`${neighbor.x},${neighbor.y}`)) continue;
                        if (this.isObstacle(neighbor, obstacles)) continue;
                        if (neighbor.x < 0 || neighbor.x >= GRID_COUNT_X || 
                            neighbor.y < 0 || neighbor.y >= GRID_COUNT_Y) continue;
                        
                        const tentativeGScore = gScore.get(`${current.x},${current.y}`) + 1;
                        
                        if (!openSet.some(n => n.x === neighbor.x && n.y === neighbor.y)) {
                            openSet.push(neighbor);
                        } else if (tentativeGScore >= gScore.get(`${neighbor.x},${neighbor.y}`)) {
                            continue;
                        }
                        
                        cameFrom.set(`${neighbor.x},${neighbor.y}`, current);
                        gScore.set(`${neighbor.x},${neighbor.y}`, tentativeGScore);
                        fScore.set(`${neighbor.x},${neighbor.y}`, tentativeGScore + this.heuristic(neighbor, target));
                    }
                }
                
                return []; // 没有找到路径
            }
            
            heuristic(node, target) {
                const dx = Math.abs(node.x - target.x);
                const dy = Math.abs(node.y - target.y);
                let multiplier = 1.0;
                
                // 根据难度调整启发式函数
                switch(this.difficulty) {
                    case 'easy': multiplier = 1.2; break;
                    case 'hard': multiplier = 0.8; break;
                }
                
                return (dx + dy) * multiplier;
            }
            
            isObstacle(node, obstacles) {
                return obstacles.some(obs => obs.x === node.x && obs.y === node.y);
            }
            
            reconstructPath(cameFrom, current) {
                const path = [current];
                while (cameFrom.has(`${current.x},${current.y}`)) {
                    current = cameFrom.get(`${current.x},${current.y}`);
                    path.unshift(current);
                }
                return path;
            }
            
            followPath() {
                if (this.path.length > 1) {
                    const next = this.path[1];
                    const head = this.game.state.snake[0];
                    
                    if (next.x > head.x) this.game.state.nextDirection = 'right';
                    else if (next.x < head.x) this.game.state.nextDirection = 'left';
                    else if (next.y > head.y) this.game.state.nextDirection = 'down';
                    else if (next.y < head.y) this.game.state.nextDirection = 'up';
                }
            }
        }
        
        // 游戏主类
        class NeonSnakeGame {
            constructor() {
                this.canvas = document.getElementById('gameCanvas');
                this.ctx = this.canvas.getContext('2d');
                this.state = new GameState();
                this.lastUpdateTime = 0;
                this.animationFrameId = null;
                this.isMobile = /Mobi|Android/i.test(navigator.userAgent);
                this.currentTheme = 'cyber';
                this.aiSnake = null;
                this.gameMode = 'classic';
                this.performanceMode = 'high';
                this.countdownElement = document.getElementById('countdown');
                this.gameHintElement = document.getElementById('gameHint');
                this.joystickActive = false;
                
                // 设置画布大小
                this.setCanvasSize();
                
                // 初始化
                this.initControls();
                this.initEventListeners();
                this.applyTheme();
                this.detectPerformance();
                
                // 显示主菜单
                document.getElementById('mainMenu').classList.remove('hidden');
                this.updateGameHint("请选择游戏模式");
            }
            
            setCanvasSize() {
                // 根据设备设置合适的画布大小
                const maxWidth = Math.min(800, window.innerWidth - 40);
                const maxHeight = Math.min(600, window.innerHeight - 200);
                
                // 保持4:3的宽高比
                const aspectRatio = 4 / 3;
                let width = maxWidth;
                let height = width / aspectRatio;
                
                if (height > maxHeight) {
                    height = maxHeight;
                    width = height * aspectRatio;
                }
                
                this.canvas.width = Math.floor(width / GRID_SIZE) * GRID_SIZE;
                this.canvas.height = Math.floor(height / GRID_SIZE) * GRID_SIZE;
                
                // 更新网格计数
                GRID_COUNT_X = Math.floor(this.canvas.width / GRID_SIZE);
                GRID_COUNT_Y = Math.floor(this.canvas.height / GRID_SIZE);
            }
            
            initControls() {
                // 键盘控制
                document.addEventListener('keydown', (e) => {
                    if (this.state.gameOver || this.state.paused || !this.state.gameStarted) return;
                    
                    switch(e.key) {
                        case 'ArrowUp':
                            if (this.state.direction !== 'down') this.state.nextDirection = 'up';
                            break;
                        case 'ArrowDown':
                            if (this.state.direction !== 'up') this.state.nextDirection = 'down';
                            break;
                        case 'ArrowLeft':
                            if (this.state.direction !== 'right') this.state.nextDirection = 'left';
                            break;
                        case 'ArrowRight':
                            if (this.state.direction !== 'left') this.state.nextDirection = 'right';
                            break;
                        case ' ':
                            this.togglePause();
                            break;
                    }
                });
                
                // 移动端虚拟摇杆
                const joystick = document.querySelector('.virtual-joystick');
                const knob = document.querySelector('.joystick-knob');
                
                joystick.addEventListener('touchstart', (e) => {
                    if (!this.state.gameStarted || this.state.paused || this.state.gameOver) return;
                    
                    this.joystickActive = true;
                    const rect = joystick.getBoundingClientRect();
                    this.joystickStartX = rect.left + rect.width / 2;
                    this.joystickStartY = rect.top + rect.height / 2;
                    knob.style.transform = 'translate(30px, 30px)';
                    e.preventDefault();
                });
                
                joystick.addEventListener('touchmove', (e) => {
                    if (!this.joystickActive || this.state.paused || !this.state.gameStarted) return;
                    
                    const touch = e.touches[0];
                    const deltaX = touch.clientX - this.joystickStartX;
                    const deltaY = touch.clientY - this.joystickStartY;
                    const angle = Math.atan2(deltaY, deltaX);
                    const distance = Math.min(30, Math.sqrt(deltaX * deltaX + deltaY * deltaY));
                    
                    const knobX = 30 + distance * Math.cos(angle);
                    const knobY = 30 + distance * Math.sin(angle);
                    knob.style.transform = `translate(${knobX - 20}px, ${knobY - 20}px)`;
                    
                    // 设置方向
                    if (distance > 15) {
                        const sector = Math.floor((angle + Math.PI + Math.PI/4) / (Math.PI/2)) % 4;
                        const directions = ['right', 'up', 'left', 'down'];
                        this.state.nextDirection = directions[sector];
                    }
                    
                    e.preventDefault();
                });
                
                joystick.addEventListener('touchend', () => {
                    this.joystickActive = false;
                    const knob = document.querySelector('.joystick-knob');
                    knob.style.transform = 'translate(30px, 30px)';
                });
                
                // 移动端暂停按钮
                document.getElementById('mobilePauseBtn').addEventListener('touchstart', (e) => {
                    if (this.state.gameStarted) {
                        this.togglePause();
                    }
                    e.preventDefault();
                });
                
                // 速度控制
                document.getElementById('speedControl').addEventListener('input', (e) => {
                    this.state.speed = 300 - e.target.value * 25;
                });
                
                // 暂停按钮
                document.getElementById('pauseBtn').addEventListener('click', () => {
                    if (this.state.gameStarted) {
                        this.togglePause();
                    }
                });
                
                // 菜单按钮
                document.getElementById('menuBtn').addEventListener('click', () => {
                    this.showMenu();
                });
                
                // 主题切换
                document.getElementById('themeSwitch').addEventListener('change', (e) => {
                    this.currentTheme = e.target.value;
                    this.applyTheme();
                });
                
                // 主菜单按钮
                document.getElementById('startClassic').addEventListener('click', () => {
                    this.startGame('classic');
                });
                
                document.getElementById('startAI').addEventListener('click', () => {
                    this.startGame('ai');
                });
                
                document.getElementById('themeSelect').addEventListener('change', (e) => {
                    this.currentTheme = e.target.value;
                    this.applyTheme();
                });
            }
            
            initEventListeners() {
                // 窗口大小调整
                window.addEventListener('resize', () => {
                    this.setCanvasSize();
                });
            }
            
            updateGameHint(message) {
                this.gameHintElement.textContent = message;
            }
            
            detectPerformance() {
                // 简单性能检测
                const start = performance.now();
                let count = 0;
                while (performance.now() - start < 5) {
                    count++;
                }
                
                if (count < 10000) {
                    this.performanceMode = 'low';
                } else if (count < 30000) {
                    this.performanceMode = 'medium';
                } else {
                    this.performanceMode = 'high';
                }
            }
            
            startGame(mode) {
                this.gameMode = mode;
                document.getElementById('mainMenu').classList.add('hidden');
                
                this.state.reset();
                this.lastUpdateTime = 0;
                
                if (this.animationFrameId) {
                    cancelAnimationFrame(this.animationFrameId);
                }
                
                if (mode === 'ai') {
                    const difficulty = document.getElementById('difficultySelect').value;
                    this.aiSnake = new AISnake(this);
                    this.aiSnake.setDifficulty(difficulty);
                    this.updateGameHint("AI对战模式 - " + (difficulty === 'easy' ? '简单' : difficulty === 'normal' ? '普通' : '困难'));
                } else {
                    this.aiSnake = null;
                    this.updateGameHint("经典模式 - 使用方向键或摇杆控制");
                }
                
                // 显示控制面板
                document.getElementById('controlPanel').classList.remove('hidden');
                document.getElementById('settingsPanel').classList.remove('hidden');
                
                // 开始倒计时
                this.startCountdown();
            }
            
            startCountdown() {
                let count = 3;
                this.countdownElement.textContent = count;
                this.countdownElement.classList.add('active');
                
                const countdownInterval = setInterval(() => {
                    count--;
                    this.countdownElement.textContent = count;
                    
                    if (count <= 0) {
                        clearInterval(countdownInterval);
                        this.countdownElement.classList.remove('active');
                        this.state.gameStarted = true;
                        // 重置蛇的初始位置和方向
                        this.state.snake = [{x: 15, y: 15}];
                        this.state.direction = 'right';
                        this.state.nextDirection = 'right';
                        this.gameLoop(0);
                    }
                }, 1000);
            }
            
            showMenu() {
                this.state.paused = true;
                document.getElementById('mainMenu').classList.remove('hidden');
                document.getElementById('controlPanel').classList.add('hidden');
                document.getElementById('settingsPanel').classList.add('hidden');
                this.updateGameHint("请选择游戏模式");
            }
            
            togglePause() {
                if (this.state.gameOver) return;
                
                this.state.paused = !this.state.paused;
                if (this.state.paused) {
                    this.updateGameHint("游戏已暂停 - 点击继续");
                } else {
                    this.updateGameHint(this.gameMode === 'ai' ? 
                        "AI对战模式 - " + (this.aiSnake.difficulty === 'easy' ? '简单' : this.aiSnake.difficulty === 'normal' ? '普通' : '困难') : 
                        "经典模式 - 使用方向键或摇杆控制");
                }
            }
            
            applyTheme() {
                const theme = THEMES[this.currentTheme];
                
                // 应用主题到UI元素
                document.body.style.backgroundColor = theme.backgroundColor;
                document.querySelector('#gameCanvas').style.borderColor = theme.uiColor;
                document.querySelector('#gameCanvas').style.boxShadow = `0 0 30px ${theme.uiColor}33`;
                document.querySelector('#score').style.color = theme.uiColor;
                document.querySelector('#score').style.textShadow = theme.textShadow;
                
                // 更新主题选择器
                document.getElementById('themeSwitch').value = this.currentTheme;
                document.getElementById('themeSelect').value = this.currentTheme;
            }
            
            gameLoop(timestamp) {
                if (!this.lastUpdateTime) this.lastUpdateTime = timestamp;
                const deltaTime = timestamp - this.lastUpdateTime;
                
                if (!this.state.paused && !this.state.gameOver && this.state.gameStarted) {
                    if (deltaTime >= this.state.speed) {
                        this.update(timestamp);
                        this.lastUpdateTime = timestamp;
                    }
                }
                
                this.render();
                this.animationFrameId = requestAnimationFrame(this.gameLoop.bind(this));
            }
            
            update(timestamp) {
                // 更新游戏状态
                this.state.direction = this.state.nextDirection;
                
                // 移动蛇
                const head = {...this.state.snake[0]};
                switch(this.state.direction) {
                    case 'up': head.y--; break;
                    case 'down': head.y++; break;
                    case 'left': head.x--; break;
                    case 'right': head.x++; break;
                }
                
                // 碰撞检测
                if (this.checkCollision(head)) {
                    this.state.gameOver = true;
                    this.gameOver();
                    return;
                }
                
                this.state.snake.unshift(head);
                
                // 食物检测
                if (head.x === this.state.food.x && head.y === this.state.food.y) {
                    this.handleFoodConsumption();
                } else {
                    this.state.snake.pop();
                }
                
                // 更新AI蛇
                if (this.aiSnake) {
                    this.aiSnake.update(timestamp);
                }
                
                // 更新粒子
                this.updateParticles();
                
                // 更新网格动画
                this.state.gridOffset = (this.state.gridOffset + 0.05) % (GRID_SIZE * 2);
            }
            
            checkCollision(head) {
                // 如果有护盾，忽略边界碰撞
                if (!this.state.shieldActive) {
                    // 边界检测
                    if (head.x < 0 || head.x >= GRID_COUNT_X || head.y < 0 || head.y >= GRID_COUNT_Y) {
                        return true;
                    }
                } else {
                    // 护盾激活时，穿墙处理
                    if (head.x < 0) head.x = GRID_COUNT_X - 1;
                    else if (head.x >= GRID_COUNT_X) head.x = 0;
                    if (head.y < 0) head.y = GRID_COUNT_Y - 1;
                    else if (head.y >= GRID_COUNT_Y) head.y = 0;
                }
                
                // 自噬检测
                return this.state.snake.some((segment, index) => {
                    return index > 0 && segment.x === head.x && segment.y === head.y;
                });
            }
            
            handleFoodConsumption() {
                const foodType = FOOD_TYPES[this.state.food.type];
                this.state.score += Math.max(0, foodType.score + this.state.comboCount * 5);
                document.getElementById('score').textContent = `SCORE: ${this.state.score}`;
                
                // 应用食物效果
                this.applyFoodEffect(foodType.effect);
                
                // 连击系统
                if (foodType.score > 0) {
                    this.state.comboCount++;
                    if (this.state.comboTimer) clearTimeout(this.state.comboTimer);
                    this.state.comboTimer = setTimeout(() => {
                        this.state.comboCount = 0;
                    }, 5000);
                }
                
                // 生成粒子
                this.createParticles(this.state.food.x, this.state.food.y, 15, foodType.color);
                
                // 生成新食物
                this.state.food = this.state.generateFood();
                
                // 难度提升
                if (this.state.score % 100 === 0) {
                    this.state.speed = Math.max(50, this.state.speed * 0.95);
                }
                
                // 震动反馈
                if (navigator.vibrate) {
                    navigator.vibrate(50);
                }
            }
            
            applyFoodEffect(effect) {
                switch(effect) {
                    case 'speed':
                        this.state.speed = Math.max(50, this.state.speed * 0.7);
                        setTimeout(() => {
                            this.state.speed = Math.min(200, this.state.speed * 1.3);
                        }, 5000);
                        break;
                    case 'shield':
                        this.state.shieldActive = true;
                        setTimeout(() => {
                            this.state.shieldActive = false;
                        }, 8000);
                        break;
                    case 'bomb':
                        // 缩短蛇身
                        const segmentsToRemove = Math.min(3, Math.floor(this.state.snake.length / 3));
                        for (let i = 0; i < segmentsToRemove; i++) {
                            if (this.state.snake.length > 1) {
                                this.state.snake.pop();
                            }
                        }
                        break;
                }
            }
            
            createParticles(x, y, count, color) {
                const theme = THEMES[this.currentTheme];
                const baseColor = color || theme.foodColor;
                
                // 根据性能模式调整粒子数量
                let adjustedCount = count;
                if (this.performanceMode === 'medium') adjustedCount = Math.floor(count * 0.7);
                if (this.performanceMode === 'low') adjustedCount = Math.floor(count * 0.3);
                
                for (let i = 0; i < adjustedCount; i++) {
                    const hue = Math.random() * 60 + 180; // 蓝色调范围
                    const particleColor = count === 1 ? `hsl(${Math.random() * 360}, 100%, 50%)` : baseColor;
                    
                    this.state.particles.push({
                        x: x * GRID_SIZE + GRID_SIZE/2,
                        y: y * GRID_SIZE + GRID_SIZE/2,
                        vx: (Math.random() - 0.5) * 10,
                        vy: (Math.random() - 0.5) * 10,
                        radius: Math.random() * 4 + 1,
                        color: particleColor,
                        life: 30 + Math.random() * 30,
                        type: Math.random() > 0.7 ? 'spark' : 'normal',
                        rotation: Math.random() * Math.PI * 2,
                        rotationSpeed: (Math.random() - 0.5) * 0.2
                    });
                }
            }
            
            updateParticles() {
                for (let i = this.state.particles.length - 1; i >= 0; i--) {
                    const p = this.state.particles[i];
                    p.x += p.vx;
                    p.y += p.vy;
                    p.vy += 0.1; // 重力
                    p.life--;
                    
                    if (p.life <= 0) {
                        this.state.particles.splice(i, 1);
                    }
                }
            }
            
            render() {
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                
                // 绘制动态网格背景
                this.drawGridBackground();
                
                // 绘制食物
                this.drawFood();
                
                // 绘制蛇
                this.drawSnake();
                
                // 绘制粒子
                this.drawParticles();
                
                // 绘制护盾效果
                if (this.state.shieldActive) {
                    this.drawShield();
                }
                
                // 游戏结束画面
                if (this.state.gameOver) {
                    this.drawGameOver();
                }
                
                // 暂停画面
                if (this.state.paused && !this.state.gameOver && this.state.gameStarted) {
                    this.drawPaused();
                }
            }
            
            drawGridBackground() {
                if (this.performanceMode === 'low') return;
                
                const theme = THEMES[this.currentTheme];
                this.ctx.strokeStyle = theme.gridColor;
                this.ctx.lineWidth = 0.5;
                
                // 根据性能模式调整网格密度
                const gridStep = this.performanceMode === 'medium' ? GRID_SIZE * 2 : GRID_SIZE;
                
                // 水平线
                for (let y = -GRID_SIZE; y < this.canvas.height; y += gridStep) {
                    const waveOffset = Math.sin((y + this.state.gridOffset) * 0.05) * 5;
                    this.ctx.beginPath();
                    this.ctx.moveTo(0, y + this.state.gridOffset + waveOffset);
                    this.ctx.lineTo(this.canvas.width, y + this.state.gridOffset + waveOffset);
                    this.ctx.stroke();
                }
                
                // 垂直线
                for (let x = -GRID_SIZE; x < this.canvas.width; x += gridStep) {
                    const waveOffset = Math.cos((x + this.state.gridOffset) * 0.05) * 5;
                    this.ctx.beginPath();
                    this.ctx.moveTo(x + this.state.gridOffset + waveOffset, 0);
                    this.ctx.lineTo(x + this.state.gridOffset + waveOffset, this.canvas.height);
                    this.ctx.stroke();
                }
            }
            
            drawFood() {
                const theme = THEMES[this.currentTheme];
                const foodType = FOOD_TYPES[this.state.food.type];
                const centerX = this.state.food.x * GRID_SIZE + GRID_SIZE/2;
                const centerY = this.state.food.y * GRID_SIZE + GRID_SIZE/2;
                
                // 食物发光效果
                if (this.performanceMode !== 'low') {
                    const gradient = this.ctx.createRadialGradient(
                        centerX, centerY, 0,
                        centerX, centerY, GRID_SIZE/2
                    );
                    gradient.addColorStop(0, foodType.color);
                    gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
                    
                    this.ctx.fillStyle = gradient;
                    this.ctx.beginPath();
                    this.ctx.arc(centerX, centerY, GRID_SIZE/2, 0, Math.PI * 2);
                    this.ctx.fill();
                }
                
                // 食物主体
                this.ctx.fillStyle = foodType.color;
                this.ctx.beginPath();
                
                if (foodType.effect) {
                    // 特殊食物绘制不同形状
                    switch(foodType.effect) {
                        case 'speed':
                            // 闪电形状
                            this.ctx.moveTo(centerX, centerY - GRID_SIZE/3);
                            this.ctx.lineTo(centerX + GRID_SIZE/3, centerY);
                            this.ctx.lineTo(centerX - GRID_SIZE/3, centerY);
                            this.ctx.lineTo(centerX, centerY + GRID_SIZE/3);
                            this.ctx.lineTo(centerX + GRID_SIZE/3, centerY);
                            break;
                        case 'shield':
                            // 盾牌形状
                            this.ctx.arc(centerX, centerY, GRID_SIZE/3, 0, Math.PI * 2);
                            break;
                        case 'bomb':
                            // 炸弹形状
                            this.ctx.arc(centerX, centerY, GRID_SIZE/3, 0, Math.PI * 2);
                            break;
                        default:
                            this.ctx.arc(centerX, centerY, GRID_SIZE/2 - 2, 0, Math.PI * 2);
                    }
                } else {
                    this.ctx.arc(centerX, centerY, GRID_SIZE/2 - 2, 0, Math.PI * 2);
                }
                
                this.ctx.fill();
                
                // 食物高光
                if (this.performanceMode !== 'low') {
                    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
                    this.ctx.beginPath();
                    this.ctx.arc(
                        centerX - GRID_SIZE/4, 
                        centerY - GRID_SIZE/4, 
                        GRID_SIZE/6, 
                        0, 
                        Math.PI * 2
                    );
                    this.ctx.fill();
                }
            }
            
            drawSnake() {
                const theme = THEMES[this.currentTheme];
                
                this.state.snake.forEach((segment, index) => {
                    const x = segment.x * GRID_SIZE;
                    const y = segment.y * GRID_SIZE;
                    
                    // 蛇身颜色渐变
                    let color;
                    if (index === 0) {
                        // 蛇头使用主题头部颜色
                        color = theme.snakeHeadColor;
                    } else {
                        // 蛇身根据长度渐变
                        const hue = 120 - index * 2;
                        const saturation = 100;
                        const lightness = 50 - Math.min(30, index * 0.5);
                        color = `hsl(${hue}, ${saturation}%, ${lightness}%)`;
                    }
                    
                    this.ctx.fillStyle = color;
                    this.ctx.fillRect(x + 1, y + 1, GRID_SIZE - 2, GRID_SIZE - 2);
                    
                    // 蛇身发光效果
                    if (this.performanceMode !== 'low') {
                        this.ctx.shadowColor = color;
                        this.ctx.shadowBlur = 10;
                        this.ctx.fillStyle = color;
                        this.ctx.fillRect(x + 1, y + 1, GRID_SIZE - 2, GRID_SIZE - 2);
                        this.ctx.shadowBlur = 0;
                    }
                    
                    // 蛇头特殊处理
                    if (index === 0) {
                        // 眼睛
                        const eyeOffsetX = this.state.direction === 'left' ? -2 : 
                                         this.state.direction === 'right' ? 2 : 0;
                        const eyeOffsetY = this.state.direction === 'up' ? -2 : 
                                         this.state.direction === 'down' ? 2 : 0;
                        
                        this.ctx.fillStyle = 'white';
                        this.ctx.beginPath();
                        this.ctx.arc(
                            x + GRID_SIZE/2 + eyeOffsetX, 
                            y + GRID_SIZE/2 + eyeOffsetY, 
                            3, 
                            0, 
                            Math.PI * 2
                        );
                        this.ctx.fill();
                        
                        this.ctx.fillStyle = 'black';
                        this.ctx.beginPath();
                        this.ctx.arc(
                            x + GRID_SIZE/2 + eyeOffsetX, 
                            y + GRID_SIZE/2 + eyeOffsetY, 
                            1.5, 
                            0, 
                            Math.PI * 2
                        );
                        this.ctx.fill();
                    }
                });
            }
            
            drawParticles() {
                this.state.particles.forEach(p => {
                    this.ctx.save();
                    this.ctx.globalAlpha = p.life / 60;
                    
                    if (p.type === 'spark' && this.performanceMode !== 'low') {
                        // 绘制星形火花
                        this.ctx.translate(p.x, p.y);
                        this.ctx.rotate(p.rotation);
                        this.ctx.fillStyle = p.color;
                        
                        this.ctx.beginPath();
                        for (let i = 0; i < 5; i++) {
                            const angle = i * Math.PI * 2 / 5;
                            this.ctx.lineTo(
                                Math.cos(angle) * p.radius * 1.5,
                                Math.sin(angle) * p.radius * 1.5
                            );
                            const innerAngle = angle + Math.PI / 5;
                            this.ctx.lineTo(
                                Math.cos(innerAngle) * p.radius * 0.5,
                                Math.sin(innerAngle) * p.radius * 0.5
                            );
                        }
                        this.ctx.closePath();
                        this.ctx.fill();
                    } else {
                        // 绘制普通圆形粒子
                        this.ctx.fillStyle = p.color;
                        this.ctx.beginPath();
                        this.ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
                        this.ctx.fill();
                    }
                
                    this.ctx.restore();
                    
                    // 更新粒子旋转
                    p.rotation += p.rotationSpeed;
                });
            }
            
            drawShield() {
                const head = this.state.snake[0];
                const centerX = head.x * GRID_SIZE + GRID_SIZE/2;
                const centerY = head.y * GRID_SIZE + GRID_SIZE/2;
                
                this.ctx.strokeStyle = 'rgba(0, 151, 255, 0.5)';
                this.ctx.lineWidth = 2;
                this.ctx.beginPath();
                this.ctx.arc(centerX, centerY, GRID_SIZE * 1.2, 0, Math.PI * 2);
                this.ctx.stroke();
                
                this.ctx.strokeStyle = 'rgba(0, 247, 255, 0.3)';
                this.ctx.lineWidth = 1;
                this.ctx.beginPath();
                this.ctx.arc(centerX, centerY, GRID_SIZE * 1.4, 0, Math.PI * 2);
                this.ctx.stroke();
            }
            
            drawGameOver() {
                const theme = THEMES[this.currentTheme];
                
                this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
                this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
                
                this.ctx.fillStyle = '#FF0000';
                this.ctx.font = 'bold 48px Orbitron';
                this.ctx.textAlign = 'center';
                this.ctx.textBaseline = 'middle';
                this.ctx.fillText('GAME OVER', this.canvas.width/2, this.canvas.height/2 - 30);
                
                this.ctx.fillStyle = theme.uiColor;
                this.ctx.font = '24px Orbitron';
                this.ctx.fillText(`FINAL SCORE: ${this.state.score}`, this.canvas.width/2, this.canvas.height/2 + 30);
                
                this.ctx.fillStyle = 'rgba(0, 247, 255, 0.5)';
                this.ctx.font = '18px Orbitron';
                this.ctx.fillText('点击菜单按钮重新开始', this.canvas.width/2, this.canvas.height/2 + 80);
            }
            
            drawPaused() {
                const theme = THEMES[this.currentTheme];
                
                this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
                
                this.ctx.fillStyle = theme.uiColor;
                this.ctx.font = 'bold 48px Orbitron';
                this.ctx.textAlign = 'center';
                this.ctx.textBaseline = 'middle';
                this.ctx.fillText('PAUSED', this.canvas.width/2, this.canvas.height/2);
            }
            
            gameOver() {
                // 震动反馈
                if (navigator.vibrate) {
                    navigator.vibrate([200, 100, 200]);
                }
                
                // 游戏结束特效
                for (let i = 0; i < 50; i++) {
                    this.createParticles(
                        this.state.snake[0].x, 
                        this.state.snake[0].y, 
                        1
                    );
                }
                
                this.updateGameHint("游戏结束 - 点击菜单按钮重新开始");
            }
        }
        
        // 启动游戏
        window.addEventListener('load', () => {
            const game = new NeonSnakeGame();
        });
    </script>
</body>
</html>